package com.sccba.emtbusiness.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.sccba.common.exception.ServiceException;
import com.sccba.common.utils.DateUtils;
import com.sccba.common.utils.SecurityUtils;
import com.sccba.common.utils.StringUtils;
import com.sccba.common.utils.http.HttpClientUtils;
import com.sccba.emtbusiness.domain.*;
import com.sccba.emtbusiness.service.IYjczFbChannelService;
import com.sccba.emtbusiness.service.IYjczFbDutyService;
import com.sccba.emtbusiness.service.IYjczFbUserService;
import com.sccba.framework.web.service.SysLoginService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sccba.emtbusiness.mapper.YjczFbInfoMapper;
import com.sccba.emtbusiness.service.IYjczFbInfoService;

/**
 * 发版版本信息Service业务层处理
 * 
 * @author lichh
 * @date 2024-04-16
 */
@Service
public class YjczFbInfoServiceImpl implements IYjczFbInfoService 
{
    private static final Logger log = LoggerFactory.getLogger(YjczFbInfoServiceImpl.class);


    @Autowired
    private YjczFbInfoMapper yjczFbInfoMapper;

    @Autowired
    private IYjczFbChannelService yjczFbChannelService;

    @Autowired
    private IYjczFbUserService yjczFbUserService;

    @Autowired
    private IYjczFbDutyService yjczFbDutyService;

    @Autowired
    private SysLoginService sysLoginService;

    /**
     * 查询发版版本信息
     * 
     * @param pkId 发版版本信息主键
     * @return 发版版本信息
     */
    @Override
    public YjczFbInfo selectYjczFbInfoByPkId(Long pkId)
    {
        YjczFbInfo fbInfo = yjczFbInfoMapper.selectYjczFbInfoByPkId(pkId);
        String gcIds = fbInfo.getGcIds();
        String qcIds = fbInfo.getQcIds();
        if (StringUtils.isNotEmpty(gcIds)) {
            fbInfo.setGeneralControlIds(Arrays.stream(gcIds.split(","))
                    .map(Long::parseLong)
                    .collect(Collectors.toList()));
        }
        if (StringUtils.isNotEmpty(qcIds)) {
            fbInfo.setQuestionCollectIds(Arrays.stream(qcIds.split(","))
                    .map(Long::parseLong)
                    .collect(Collectors.toList()));
        }
        return fbInfo;
    }

    /**
     * 查询发版版本信息列表
     * 
     * @param yjczFbInfo 发版版本信息
     * @return 发版版本信息
     */
    @Override
//    @DataScope(scopeByChannel = true, channelAlias = "b", channelIdField = "channel_id")
    public List<YjczFbInfo> selectYjczFbInfoList(YjczFbInfo yjczFbInfo)
    {
        List<YjczFbInfo> list = yjczFbInfoMapper.selectYjczFbInfoList(yjczFbInfo);
        if (!list.isEmpty()) {
            List<Long> fbIds = list.stream().map(item -> item.getPkId()).collect(Collectors.toList());
            List<YjczFbUser> fbUsers = yjczFbUserService.selectListByFbIds(fbIds);
            Map<Integer, Map<Long, String>> typeAndFbIdAndUserNames = fbUsers.stream().collect(
                    Collectors.groupingBy(
                            YjczFbUser::getType,
                            Collectors.groupingBy(
                                    YjczFbUser::getFbId,
                                    Collectors.mapping(YjczFbUser::getUserName, Collectors.joining(","))
                            )
                    )
            );
            Map<Integer, Map<Long, String>> typeAndFbIdAndUserIds = fbUsers.stream().collect(
                    Collectors.groupingBy(
                            YjczFbUser::getType,
                            Collectors.groupingBy(
                                    YjczFbUser::getFbId,
                                    Collectors.mapping(k -> String.valueOf(k.getUserId()), Collectors.joining(","))
                            )
                    )
            );
            Map<Long, String> generalControlNameMap = typeAndFbIdAndUserNames.get(GENERAL_CONTROL_USER_TYPE);
            Map<Long, String> questionCollectNameMap = typeAndFbIdAndUserNames.get(QUESTION_COLLECT_USER_TYPE);
            Map<Long, String> generalControlIdMap = typeAndFbIdAndUserIds.get(GENERAL_CONTROL_USER_TYPE);
            Map<Long, String> questionCollectIdMap = typeAndFbIdAndUserIds.get(QUESTION_COLLECT_USER_TYPE);
            for (YjczFbInfo fbInfo : list) {
                Long fbId = fbInfo.getPkId();
                if (null != generalControlNameMap) {
                    fbInfo.setFbGeneralControlName(generalControlNameMap.get(fbId));
                    fbInfo.setGcIds(generalControlIdMap.get(fbId));
                }
                if (null != questionCollectNameMap) {
                    fbInfo.setQuestionCollectName(questionCollectNameMap.get(fbId));
                    fbInfo.setQcIds(questionCollectIdMap.get(fbId));
                }
            }
        }
        return list;
    }

    /**
     * 新增发版版本信息
     * 
     * @param yjczFbInfo 发版版本信息
     * @return 结果
     */
    @Override
    public int insertYjczFbInfo(YjczFbInfo yjczFbInfo)
    {
        yjczFbInfo.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
        yjczFbInfo.setCreateTime(DateUtils.getNowDate());
        int i = yjczFbInfoMapper.insertYjczFbInfo(yjczFbInfo);
        handleFbChannelList(yjczFbInfo);
        insertFbUserByFbInfo(yjczFbInfo);
        return i;
    }


    private static final int GENERAL_CONTROL_USER_TYPE = 0;
    private static final int QUESTION_COLLECT_USER_TYPE = 1;

    private void insertFbUserByFbInfo (YjczFbInfo yjczFbInfo) {
        List<YjczFbUser> list = new ArrayList<>();
        List<Long> generalControlIds = yjczFbInfo.getGeneralControlIds();
        List<Long> questionCollectIds = yjczFbInfo.getQuestionCollectIds();
        Long fbId = yjczFbInfo.getPkId();
        setFbUsersToList(list, generalControlIds, fbId, GENERAL_CONTROL_USER_TYPE);
        setFbUsersToList(list, questionCollectIds, fbId, QUESTION_COLLECT_USER_TYPE);
        if (!list.isEmpty()) {
            yjczFbUserService.batchInsert(list);
        }
    }
    private void setFbUsersToList (List<YjczFbUser> list, List<Long> userIds, Long fbId, int type) {
        if (null == userIds || userIds.isEmpty()) {
            return;
        }
        YjczFbUser yjczFbUser;
        for (Long userId : userIds) {
            yjczFbUser = new YjczFbUser();
            yjczFbUser.setUserId(userId);
            yjczFbUser.setFbId(fbId);
            yjczFbUser.setType(type);
            list.add(yjczFbUser);
        }
    }

    /**
     * 修改发版版本信息
     * 
     * @param yjczFbInfo 发版版本信息
     * @return 结果
     */
    @Override
    public int updateYjczFbInfo(YjczFbInfo yjczFbInfo)
    {
        yjczFbInfo.setUpdateBy(String.valueOf(SecurityUtils.getUserId()));
        yjczFbInfo.setUpdateTime(DateUtils.getNowDate());
        int i = yjczFbInfoMapper.updateYjczFbInfo(yjczFbInfo);
        handleFbChannelList(yjczFbInfo);
        yjczFbUserService.deleteByFbId(yjczFbInfo.getPkId());
        insertFbUserByFbInfo(yjczFbInfo);
        return i;
    }

    private void handleFbChannelList (YjczFbInfo yjczFbInfo) {
        Long pkId = yjczFbInfo.getPkId();
        String channelListIds = yjczFbInfo.getChannelListIds();
        List<YjczFbChannel> fbChannelList = new ArrayList<>();
        if (StringUtils.isNotEmpty(channelListIds)) {
            YjczFbChannel fbChannel;
            String[] channelListIdArr = channelListIds.split(",");
            for (String channelId : channelListIdArr) {
                fbChannel = new YjczFbChannel();
                fbChannel.setFbId(pkId);
                fbChannel.setChannelId(Long.parseLong(channelId));
                fbChannelList.add(fbChannel);
            }
        }
        yjczFbChannelService.insertFbChannelList(pkId, fbChannelList);
    }

    /**
     * 批量删除发版版本信息
     * 
     * @param pkIds 需要删除的发版版本信息主键
     * @return 结果
     */
    @Override
    public int deleteYjczFbInfoByPkIds(Long[] pkIds)
    {
        return yjczFbInfoMapper.updateYjczToRemove(pkIds);
    }

    /**
     * 删除发版版本信息信息
     * 
     * @param pkId 发版版本信息主键
     * @return 结果
     */
    @Override
    public int deleteYjczFbInfoByPkId(Long pkId)
    {
        return yjczFbInfoMapper.deleteYjczFbInfoByPkId(pkId);
    }

    @Override
//    @DataScope(scopeByChannel = true, channelAlias = "b", channelIdField = "channel_id")
    public List<YjczFbInfo> selectFbInfoList(YjczFbInfo yjczFbInfo) {
        return yjczFbInfoMapper.selectFbInfoList(yjczFbInfo);
    }

    private static final String ERR_CODE_KEY = "errcode";
    private static final String ERR_MSG_KEY = "errmsg";
    private static final String CHAT_ID_KEY = "chatid";


    @Override
    public void createChatGroup(Long fbId) {
        if (null == fbId || 0 == fbId) {
            return;
        }
        YjczFbInfo fbInfo = yjczFbInfoMapper.selectYjczFbInfoByPkId(fbId);
        if (StringUtils.isNotEmpty(fbInfo.getFbChatId())) {
            throw new ServiceException("该次发版已有E动群聊，不可重复创建群聊");
        }
        List<String> userNameList = yjczFbDutyService.selectUserIdsByFbId(fbId);
        if (null == userNameList || userNameList.isEmpty()) {
            throw new ServiceException("本次发版不涉及任何人员，无法创建群聊");
        }
        // 将操作人一起拉进群聊
        String currUserName = SecurityUtils.getUsername();
        if (!userNameList.contains(currUserName)) {
            userNameList.add(currUserName);
        }
        String gcUserName = yjczFbUserService.selectGcUserNameByFbId(fbId);
        String accessToken = sysLoginService.getAccessToken();
        String createChatGroupUrl = "http://7.22.1.64/cgi-bin/appchat/create?access_token=" + accessToken;
        Map<String, Object> params = new HashMap<>();
        params.put("name", fbInfo.getFbName() + "值班群");
        params.put("owner", StringUtils.isEmpty(gcUserName) ? userNameList.get(0) : gcUserName);
        params.put("userlist", userNameList);
        String response = HttpClientUtils.sendPost(createChatGroupUrl, params);
        String chatId;
        JSONObject jsonObject;
        try {
            jsonObject = JSON.parseObject(response);
            String errCode = "响应报文为null";
            String errMsg;
            if (null == jsonObject || null == (errCode = jsonObject.getString(ERR_CODE_KEY)) || !"0".equals(errCode)) {
                errMsg = jsonObject.getString(ERR_MSG_KEY);
                log.error("errCode为{}，errMsg为：{}", errCode, errMsg);
                throw new ServiceException("创建E动群聊失败，清联系管理员！错误信息：" + errMsg);
            }
            chatId = jsonObject.getString(CHAT_ID_KEY);
        } catch (Exception ex) {
            log.error("异常信息:{}", ex.getMessage());
            throw new ServiceException("创建E动群聊失败，清联系管理员！");
        }
        // 推送消息
        pushChatMsg(accessToken, fbInfo.getFbName(), chatId);
        fbInfo.setFbChatId(chatId);
        yjczFbInfoMapper.updateYjczFbInfo(fbInfo);
    }

    private void pushChatMsg (String accessToken, String fbName, String chatId) {
        String url = "http://7.22.1.64/cgi-bin/appchat/send?access_token=" + accessToken;
        String msg = String.format("%s值班群创建成功，群聊id为：%s", fbName, chatId);
        Map<String, Object> contentMap = new HashMap<>();
        contentMap.put("content", msg);
        Map<String, Object> params = new HashMap<>();
        params.put("chatid", chatId);
        params.put("msgtype", "text");
        params.put("text", contentMap);
        String response = HttpClientUtils.sendPost(url, params);
        JSONObject jsonObject;
        try {
            jsonObject = JSON.parseObject(response);
            String errCode = "响应报文为null";
            String errMsg;
            if (null == jsonObject || null == (errCode = jsonObject.getString(ERR_CODE_KEY)) || !"0".equals(errCode)) {
                errMsg = jsonObject.getString(ERR_MSG_KEY);
                log.error("errCode为{}，errMsg为：{}", errCode, errMsg);
                throw new ServiceException("发送E动群聊消息失败！错误信息：" + errMsg);
            }
        } catch (Exception ex) {
            log.error("异常信息:{}", ex.getMessage());
            throw new ServiceException("发送E动群聊消息失败！");
        }
    }
}
